package com.bw.journal.list

import android.view.LayoutInflater
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewbinding.ViewBinding
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bw.common.mvi.BaseActivity
import com.bw.journal.databinding.ActivityJournalBinding
import com.bw.widget.decoration.JournalDecoration
import com.bw.widget.header.MDMRefreshHeader
import com.scwang.smart.refresh.footer.ClassicsFooter
import kotlinx.coroutines.launch

@Route(path = "/journal/JournalActivity")
class JournalActivity : BaseActivity<ActivityJournalBinding,JournalListViewModel>(){

    private val journalAdapter : JournalAdapter by lazy { JournalAdapter() }

    override fun createVM(): JournalListViewModel {
        return viewModels<JournalListViewModel>().value
    }

    override fun initView() {
        v.journalListPage.titleTv.text = "工作汇报"
        v.journalListPage.backImg.setOnClickListener { finish() }
        v.journalAddImg.setOnClickListener {
            ARouter.getInstance().build("/journal/JournalInsertActivity").navigation()
        }
        v.journalListSmart.setRefreshHeader(MDMRefreshHeader(this,null))
        v.journalListSmart.setRefreshFooter(ClassicsFooter(this))
        v.journalListSmart.setOnRefreshListener {
            vm.refreshJournal(1)
        }
        v.journalListSmart.setOnLoadMoreListener {
            vm.loadJournal(1)
        }
        val manager = LinearLayoutManager(this)
        manager.orientation = LinearLayoutManager.VERTICAL
        v.journalListRv.layoutManager = manager
        v.journalListRv.addItemDecoration(JournalDecoration(this))
        v.journalListRv.adapter = journalAdapter
    }

    override fun onRestart() {
        super.onRestart()
        initData()
    }

    override fun initData() {
        vm.refreshJournal(1)
    }

    override fun bindState() {
        lifecycleScope.launch {
            vm.mutableContainer.uiStateFlow.collect{
                if(it.refreshState)
                    journalAdapter.setNewInstance(it.datas)
                if (it.loadState)
                    journalAdapter.adds(it.datas)
            }
        }
    }

    override fun createViewBinding(): ViewBinding {
        return ActivityJournalBinding.inflate(LayoutInflater.from(this))
    }
}